import redis
import time
import requests


class Delay_out:
    def __init__(self):
        self.r = redis.Redis(decode_responses=True)
        self.key = 'chat_out'

    def add(self, uid, delay=10):
        print("延时队列入队，%s秒后执行删除uid%s的任务" % (delay, uid))
        res = self.r.zrange(self.key, 0, -1)
        if uid in res:
            self.r.zrem(self.key, uid)
        else:
            pass
        self.r.zadd(self.key, {uid: time.time() + delay})

        # 删除延时任务

    def remove(self, uid):

        return self.r.zrem(self.key, uid)
        # 出队逻辑

    def pop(self):
        # 获取队列
        res = self.r.zrangebyscore(self.key, 0, time.time(), 0, 1, withscores=False)
        print(res)
        if res == None:
            print("暂无延时任务")
            return False
        if len(res) == 1:
            print("延时任务到期，返回执行任务的uid%s" % res[0])
            return res[0]
        else:
            print("延时任务没有到时间")
            return False


do = Delay_out()
# do.add(1, 10)
# do.add(2, 5)
# res = do.pop()
# do.remove(res)
r = redis.Redis(decode_responses=True)
while True:
    print("开始延时服务")
    res = do.pop()
    if res is not False:
        do.remove(res)
        do.add(res)
        r.rpop('send')
        print(11111)
        res = requests.get("http://localhost:8000/sends/", params={'data': 'ok'})
    time.sleep(1)
